﻿using StaffingSystem.EF;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace StaffingSystem.Business
{
    public class Pagelist
    {
        Management db;
        public PageModel<T> GetPageList<T>(PageModel<T> page)
        {
            List<T> memberList = null;
            try
            {
                db = new Management();
                //使用拼接字符串的方式，将要执行的存储过程名称以及参数拼接在一起
                StringBuilder procString = new StringBuilder();
                procString.Append("System_Paging_proc");
                procString.Append(" @sys_PageIndex,");
                procString.Append("@sys_PageSize,");
                procString.Append("@sys_Table,");
                procString.Append("@sys_Key,");
                procString.Append("@sys_Where,");
                procString.Append("@sys_Order,");
                procString.Append("@sys_AscOrDesc,");
                procString.Append("@pageCount out,");
                procString.Append("@recordCount out");

                SqlParameter pageCount = new SqlParameter("@pageCount", SqlDbType.Int);
                pageCount.Direction = ParameterDirection.Output;//表明此参数是输出型参数                
                SqlParameter recordCount = new SqlParameter("@recordCount", SqlDbType.Int);
                recordCount.Direction = ParameterDirection.Output;//表明此参数是输出型参数
                //执行存储过程并将具体参数对应的值传入存储过程中
                SqlParameter[] parameters = {
                   new SqlParameter("@sys_PageIndex",page.PageNumber),
                    new SqlParameter("@sys_PageSize",page.PageSize),
                    new SqlParameter("@sys_Table",page.TableName),
                    new SqlParameter("@sys_Key",page.PageKey),
                    new SqlParameter("@sys_Where",page.Where),
                    new SqlParameter("@sys_Order",page.OrderID),
                    new SqlParameter("@sys_AscOrDesc",page.AscOrDesc),
                    pageCount,
                    recordCount
                };
                memberList = db.Database.SqlQuery<T>(procString.ToString(), parameters).ToList();
                var totalItems = recordCount.Value != null ? (int)recordCount.Value : 0;//总记录数
                var pagecount = pageCount.Value != null ? (int)pageCount.Value : 0; //总页数
                page.RowCount = totalItems;
                page.PageCount = pagecount;
                page.DataList = memberList;
                return page;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
